package listener;

import javax.swing.JComponent;

import protocal.DataPackage;
import protocal.DataPackage.MessageType;
import adapter.UserListAdapter;
import data.DataUserList;

public class UserListListener extends Listener {
	
//	private final static Logger logger = LogManager.getLogger(UserListListener.class);
	
	private JComponent jComponent;
	private Listener listener;
	private UserListAdapter adapter;
	private DataUserList dataUserList;

	public UserListListener(JComponent jComponent,Listener listener) {
		this.jComponent = jComponent;
		this.listener = listener;
		adapter =  new UserListAdapter(this.jComponent, DataUserList.getInstance().getUserList());
		dataUserList = DataUserList.getInstance();
	}

	@Override
	public void listen(DataPackage dataPackage) {
			listener.listen(dataPackage);
			listListen(dataPackage);
			loginListen(dataPackage);
			logoutListen(dataPackage);
	}
	
	private void listListen(DataPackage dataPackage){
		if (dataPackage.getMessageType()==MessageType.LIST) {
			if (dataPackage.getMessageData()!=null) {
				String[] names = dataPackage.getMessageData().split("\\\\");
				dataUserList.removeAll();
				for (int i = 0; i < names.length; i++) {
					dataUserList.add(names[i]);
				}
				
			}
			adapter.adapter();
		}
	}
	
	private void loginListen(DataPackage dataPackage){
		if (dataPackage.getMessageType()==MessageType.LOGIN) {
			dataUserList.add(dataPackage.getMessageData());
			adapter.adapter(dataPackage);
		}
	}
	
	private void logoutListen(DataPackage dataPackage){
			if (dataPackage.getMessageType()==MessageType.LOGOUT) {
				dataUserList.delete(dataPackage.getMessageData());
				adapter.adapter(dataPackage);
			}
		}

}
